<template>
  <view class="container">
    <!-- 用户头像 -->
    <view class="avatar-section" @click="changeAvatar">
      <image :src="form.avatar" class="avatar"></image>
      <text class="avatar-tip">点击更换头像</text>
    </view>

    <!-- 表单区域 -->
    <view class="form">
		<view class="form-item">
		  <text class="label">用户账号</text>
		  <input 
		    v-model="form.account" 
		    placeholder="用户账号"
		    class="input"
			disabled
		  />
		</view>
      <view class="form-item">
        <text class="label">昵称</text>
        <input 
          v-model="form.nickname" 
          placeholder="请输入昵称"
          class="input"
        />
      </view>
      <view class="form-item">
        <text class="label">性别</text>
        <input 
          v-model="form.gender" 
          placeholder="请输入昵称"
          class="input"
        />
      </view>
      <view class="form-item">
        <text class="label">手机号</text>
        <input 
          v-model="form.phoneNumber" 
          placeholder="请输入手机号"
          class="input"
          type="number"
        />
      </view>
	<view class="input-group">
		<text class="label">验证码</text>
		<input v-model="verificationCode" class="input" placeholder="请输入验证码" maxlength="6" />
		<view class="input-group">
			<img class="sms-btn" :src="yanzhengma" @click="getYZM" alt="验证码">
		</view>
	</view>

      <view class="form-item">
        <text class="label">真实姓名</text>
        <input 
          v-model="form.realName" 
          placeholder="请输入真实姓名"
          class="input"
        />
      </view>
	  <view class="form-item">
	    <text class="label">家庭编码</text>
	    <input 
	      v-model="form.familyCode" 
	      placeholder="家庭编码"
	      class="input"
		  disabled
	    />
	  </view>
	  <view class="form-item">
	    <text class="label">户主信息</text>
	    <input 
	      v-model="form.familyUserName" 
	      placeholder="家庭编码"
	      class="input"
	  	  disabled
	    />
	  </view>
    </view>

    <!-- 保存按钮 -->
    <button class="save-btn" @click="handleSave">保存修改</button>
  </view>
</template>

<script setup>
import { ref ,onMounted} from 'vue'
	const smsCode = ref('')
	const yanzhengma = ref('')
	const verifyCodeToken=ref('')
	const verificationCode=ref('')
	// 表单数据
	const form = ref({
	})
	onMounted(() => {
			setUserInfo()
			getYZM()
	})
	const setUserInfo=()=>{
		// 获取当前登录用户的信息
		uni.request({
				url: 'http://localhost:8081/sysUser/userInfo',
				method: "GET",
				header: {
				  'Authorization': 'Bearer ' + uni.getStorageSync('token') // 从本地存储获取token
				},
				success: (res) => {
					if(res.data.code=="200"){
						console.log("结果为",res)
						form.value=res.data.result
					}else{
						uni.showToast({ title: '查询用户失败', icon: 'none' })
					}
				}
			});
	}
	/**
	 * 获取验证码
	 */
	const getYZM = async () => {
		try {
			const res = await uni.request({
				url: 'http://localhost:8081/sysUser/generate/verify/code',
				method: 'GET'
			})
			console.log(res)
			yanzhengma.value = `data:image/jpeg;base64,${res.data.result.image}`
			verifyCodeToken.value=res.data.result.verifyCodeToken
		} catch (error) {
			console.error('请求失败:', error)
			uni.showToast({
				title: "验证码获取失败",
				icon: 'none'
			})
		}
	}
// 更换头像
const changeAvatar = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sourceType: ['album', 'camera']
    })
	//上传
	uni.uploadFile({
		url: 'http://localhost:8081/file/upload',
		filePath: res.tempFilePaths[0], //图片路径
		name: 'file',
		header: {
		  'Authorization': 'Bearer ' + uni.getStorageSync('token') // 从本地存储获取token
		},
		success: (uploadFileRes) => {
			const responseData = JSON.parse(uploadFileRes.data)
			console.log("本次添加图片id为",responseData.result.fileKey)
			if(res.tempFilePaths[0]){
			  form.value.avatar = res.tempFilePaths[0]
			}
			console.log(imageListId)
		}
	});
	
  } catch {
    uni.showToast({ title: '选择头像失败', icon: 'none' })
  }
}

// 保存数据
const handleSave =() => {
  console.log("点击修改按钮")
  if(!form.value.nickname.trim()) {
    return uni.showToast({ title: '昵称不能为空', icon: 'none' })
  }
  
  if(!/^1[3-9]\d{9}$/.test(form.value.phoneNumber)) {
    return uni.showToast({ title: '手机号格式错误', icon: 'none' })
  }

  uni.showLoading({ title: '保存中...' })
  try {
    uni.request({
      url: 'http://localhost:8081/sysUser/userImprove',
      method: 'POST',
      data: form.value,
	  header: {
	    'Authorization': 'Bearer ' + uni.getStorageSync('token') // 从本地存储获取token
	  }
    }).then((res)=>{
			if(res.data.code === '200') {
			    console.log("结果为",res)
                setUserInfo()
				uni.removeStorageSync('userInfo');
				uni.showToast({
					title: '修改用户成功',
					icon: 'success'
				})
			} else {
				console.log("失败结果为",res)
				getYZM()
				uni.showToast({
					title: res.data.message || '修改异常',
					icon: 'none'
				})
			}
	})
  } catch {
    uni.showToast({ title: '保存失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}
</script>

<style lang="scss">
.container {
  padding: 40rpx;
}
.input-group {
		margin-bottom: 40rpx;
		position: relative;
	}
	.sms-btn {
		position: absolute;
		right: 0;
		bottom: 0;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 24rpx;
		padding: 0 30rpx;
		background-color: #f0f0f0;
		border-radius: 8rpx;
	}

	.sms-btn[disabled] {
		background-color: #eee;
		color: #999;
	}
.label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
	}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 60rpx 0;
  
  .avatar {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    margin-bottom: 20rpx;
    border: 2rpx solid #eee;
  }
  
  .avatar-tip {
    color: #666;
    font-size: 28rpx;
  }
}

.form {
  background: #fff;
  border-radius: 16rpx;
  padding: 0 30rpx;
  
  .form-item {
    display: flex;
    align-items: center;
    height: 100rpx;
    border-bottom: 1rpx solid #eee;
    
    &:last-child {
      border: none;
    }
    
    .label {
      width: 160rpx;
      font-size: 30rpx;
      color: #333;
    }
    
    .input {
      flex: 1;
      height: 100%;
      text-align: right;
      font-size: 30rpx;
      color: #666;
    }
  }
}

.save-btn {
  margin-top: 60rpx;
  background: #007aff;
  color: #fff;
  border-radius: 50rpx;
  
  &::after {
    border: none;
  }
  
  &:active {
    opacity: 0.8;
  }
}
</style>